package com.idea.relax.log.listener;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.LoggerContextListener;
import ch.qos.logback.core.spi.ContextAwareBase;
import com.idea.relax.log.appender.ILogbackAppender;
import lombok.AllArgsConstructor;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author salad
 * @date: 2022/12/01
 * @description: logback日志的监听器
 */
@AllArgsConstructor
public class LogbackLoggerContextListener extends ContextAwareBase implements LoggerContextListener {

    private final List<ILogbackAppender> appenderList;

    @Override
    public boolean isResetResistant() {
        return true;
    }

    @Override
    public void onStart(LoggerContext context) {
        for (ILogbackAppender appender : sortAppenderList()) {
            appender.start(context);
        }
    }

    @Override
    public void onReset(LoggerContext context) {
        for (ILogbackAppender appender : sortAppenderList()) {
            appender.reset(context);
        }
    }

    @Override
    public void onStop(LoggerContext context) {
        // Nothing to do.
    }

    @Override
    public void onLevelChange(Logger logger, Level level) {
        // Nothing to do.
    }

    private List<ILogbackAppender> sortAppenderList() {
        return appenderList
                .stream().sorted().collect(Collectors.toList());
    }

}
